package com.cug.nageoffer.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cug.nageoffer.common.exception.GlobalException;
import com.cug.nageoffer.controller.ChatUserController;
import com.cug.nageoffer.model.vo.ResultCodeEnum;
import com.cug.nageoffer.model.vo.UserMsgVo;
import com.cug.nageoffer.service.ChatUserService;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chat/{username}")
@Component
@Slf4j
public class WebSocketApplication {

    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    private static ChatUserController chatUserController;

    private String username;

    @Autowired
    public void setChatUserController(ChatUserController chatUserController){
        WebSocketApplication.chatUserController = chatUserController;
    }

    private static ChatUserService chatUserService;

    @Autowired
    public void setChatUserService(ChatUserService chatUserService){
        WebSocketApplication.chatUserService = chatUserService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username){
        sessionMap.put(username, session);
        log.info("用户{}已上线",username);
    }

    @OnMessage
    public void onMessage(String message){

        LocalDateTime now = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        String nowTime = now.format(dateTimeFormatter);

        UserMsgVo userMsgVo = new UserMsgVo();
        userMsgVo.setTimestamp(nowTime);
        JSONObject jsonObject = JSON.parseObject(message);
        String target = jsonObject.getString("target");
        String sender = jsonObject.getString("sender");
        String msg = jsonObject.getString("msg");
        userMsgVo.setReceiverName(target);
        userMsgVo.setSenderName(sender);
        userMsgVo.setContent(msg);
        Session targetSession = sessionMap.get(target);
        if(targetSession == null){
            log.error("用户{}当前不在线",target);
            try{
                chatUserService.saveHistoryMsg(userMsgVo);
            }catch (Exception e){
                log.error("发生了异常：{}", Arrays.toString(e.getStackTrace()));
                throw new GlobalException(ResultCodeEnum.DATA_ERROR);
            }
            return;
        }

        this.sendMessageToOneUser(userMsgVo,targetSession);

    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        sessionMap.remove(username);

    }

    private void sendMessageToOneUser(UserMsgVo userMsgVo, Session targetSession)  {

        try {
            targetSession.getBasicRemote().sendText(JSONObject.toJSONString(userMsgVo));
            try{
                chatUserService.saveHistoryMsg(userMsgVo);
            }catch (Exception e){
                log.error("发生了异常：{}", Arrays.toString(e.getStackTrace()));
                throw new GlobalException(ResultCodeEnum.DATA_ERROR);
            }
        } catch (IOException e) {
            log.error("发生了");
            throw new RuntimeException(e);
        }

    }


}
